package com.cqcomponents.servlets;

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;

@SlingServlet(selectors = { "overlay", "infinity" }, extensions = { "json" }, resourceTypes = { "/apps/cqcomponents/servlets/dialogrenderer" })
public class DialogGeneratorServlet extends SlingSafeMethodsServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1666645813868001191L;

	@Override
	protected void doGet(SlingHttpServletRequest request,
			SlingHttpServletResponse response) throws ServletException,
			IOException {

		Resource resource = request.getResource();
		String resourcePath = resource.getPath();
		ValueMap valueMap = resource.adaptTo(ValueMap.class);
		String componentName = StringUtils.substringAfterLast(
				StringUtils.substringBeforeLast(resourcePath, "/dialog"), "/")
				.toLowerCase();

		String title = valueMap.get("title", "Edit Component");
		String width = valueMap.get("width", "620");
		String height = valueMap.get("height", "320");
		String dialog = "{'xtype':'dialog','title':'"
				+ title
				+ "','cls':'twbs_on'"
				+ ",'height':'"
				+ height
				+ "'"
				+ ",'width':'"
				+ width
				+ "','jcr:primaryType':'cq:Dialog','items':{'xtype':'panel',"
				+ "'jcr:primaryType':'cq:Widget','items':{'jcr:primaryType':'cq:WidgetCollection',"
				+ "'widget':{'xtype':'" + componentName + "_widget','cls':'"
				+ componentName + "_widget','jcr:primaryType':'cq:Widget'}}}}";
		response.getWriter().write(dialog);
	}

}
